/**
 * @desc    模板管理
 * @author  刘贺[of2220]
 * @company qianmi.com
 * @Date    2017/2/10
 */
('use strict');
import * as mongoose from 'mongoose';
import TemplateInfoModel from '../dao/templateInfo/template-info-model';

export default class TemplateInfoService {
  //保存templateInfo templateCode唯一ID
  static upsertTplInfo(templateInfo: any) {
    let conditions = { templateCode: templateInfo.templateCode };
    let options = { upsert: true };
    delete templateInfo._id;
    return new Promise((resolve, reject) => {
      TemplateInfoModel.update(conditions, templateInfo, options).exec((err, res) => {
        err ? reject(err) : resolve(res);
      });
    });
  }

  static getTemplateInfoByIdOrCode(id: string) {
    let conditions = mongoose.Types.ObjectId.isValid(id)
      ? { $or: [{ _id: id }, { templateCode: id }] }
      : { templateCode: id };
    let selectOpt =
      '-acceptBars -pluginBars -adapterBars -dependenciesBar -barDefaultPropsMap -nsTransferMap -children -templateConfig';
    return new Promise((resolve, reject) => {
      TemplateInfoModel.findOne(conditions).select(selectOpt).exec((err, res) => {
        err ? reject(err) : resolve(res);
      });
    });
  }

  static async getTemplateList({
    systemCode,
    pageNo = -1,
    pageSize = 10,
    isShow,
    platform,
    includePageTypeList = [],
    excludePageTypeList = []
  }: {
    systemCode: string;
    pageNo?: number;
    pageSize?: number;
    isShow?: any;
    platform?: string;
    includePageTypeList?: string[];
    excludePageTypeList?: string[];
  }) {
    let conditions = { systemCode };
    if (typeof isShow === 'boolean') {
      Object.assign(conditions, { isShow });
    }
    platform && Object.assign(conditions, { platform });
    includePageTypeList &&
      includePageTypeList.length &&
      Object.assign(conditions, { pageType: { $in: includePageTypeList } });
    excludePageTypeList &&
      excludePageTypeList.length &&
      Object.assign(conditions, { pageType: { $nin: excludePageTypeList } });
    let selectOpt =
      '-acceptBars -pluginBars -adapterBars -dependenciesBar -barDefaultPropsMap -nsTransferMap -children -templateConfig';
    try {
      let totalCount = await new Promise((resolve, reject) => {
        TemplateInfoModel.count(conditions).exec((err, res) => {
          err ? reject(err) : resolve(res);
        });
      });

      let templateList = pageNo === -1
        ? await new Promise((resolve, reject) => {
            TemplateInfoModel.find(conditions).select(selectOpt).sort({ updateTime: -1 }).exec((err, res) => {
              err ? reject(err) : resolve(res);
            });
          })
        : await new Promise((resolve, reject) => {
            TemplateInfoModel.aggregate([
              { $match: conditions },
              { $sort: { updateTime: -1 } },
              { $skip: pageNo * pageSize },
              { $limit: pageSize }
            ]).exec((err, res) => {
              err ? reject(err) : resolve(res);
            });
          });
      return { totalCount, templateList };
    } catch (e) {
      throw e;
    }
  }

  static getTplListByTplCodes(tplCodes: string[]): Promise<Array<any>> {
    let selectOpt =
      '-acceptBars -pluginBars -adapterBars -dependenciesBar -barDefaultPropsMap -nsTransferMap -children -templateConfig';
    return new Promise((resolve, reject) => {
      TemplateInfoModel.find({ templateCode: { $in: tplCodes } }).select(selectOpt).exec((err, res) => {
        err ? reject(err) : resolve(res && res.length ? JSON.parse(JSON.stringify(res)) : []);
      });
    });
  }

  static getPublishType(id: string) {
    let conditions = mongoose.Types.ObjectId.isValid(id)
      ? { $or: [{ _id: id }, { templateCode: id }] }
      : { templateCode: id };
    return new Promise((resolve, reject) => {
      TemplateInfoModel.findOne(conditions).select('publishType').lean().exec((err, res: any) => {
        err ? reject(err) : resolve((res && res.publishType) || '');
      });
    });
  }
}
